package net.huashitong.synthetical.TaskJob.web;

import com.sirdc.modules.core.exceptions.SystemException;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.security.SysPrincipal;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.synthetical.AddressBook.entity.AddressBook;
import net.huashitong.synthetical.AddressBook.entity.AddressBookUser;
import net.huashitong.synthetical.AddressBook.filter.BookFilter;
import net.huashitong.synthetical.AddressBook.service.AddressBookService;
import net.huashitong.synthetical.AddressBook.service.AddressBookUserService;
import net.huashitong.synthetical.TaskJob.Entity.TaskJob;
import net.huashitong.synthetical.TaskJob.Entity.TaskProcess;
import net.huashitong.synthetical.TaskJob.Entity.TaskSituation;
import net.huashitong.synthetical.TaskJob.Service.ExportService;
import net.huashitong.synthetical.TaskJob.Service.TaskJobService;
import net.huashitong.synthetical.TaskJob.Service.TaskProcessService;
import net.huashitong.synthetical.TaskJob.Service.TaskSituationService;
import net.huashitong.synthetical.TaskJob.databean.FlowLineBean;
import net.huashitong.synthetical.TaskJob.databean.GraphBean;
import net.huashitong.synthetical.TaskJob.filter.TaskJobFilter;
import net.huashitong.synthetical.TaskJob.filter.TaskProcessFilter;
import net.huashitong.synthetical.TaskJob.filter.TaskSituationFilter;
import net.huashitong.synthetical.databean.ExportHeads;
import net.huashitong.synthetical.jobOversee.Service.JobGroupService;
import net.huashitong.synthetical.jobOversee.entity.JobGroup;
import net.huashitong.synthetical.jobOversee.filter.JobGroupFilter;
import net.huashitong.util.UtilsTools;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;

import static net.huashitong.util.UtilsTools.getNowDate;

@Controller
@RequestMapping("/jobmanages")
public class JobManageCtrl extends JsonBaseController {


    @Autowired
    private TaskJobService taskJobService;
    @Autowired
    private AddressBookService bookService;
    @Autowired
    private TaskProcessService processService;
    @Autowired
    private AddressBookUserService bookUserService;
    @Autowired
    private ExportService exportService;

    @Autowired
    private JobGroupService jobGroupService;

    @Override
    protected String getView(String s) {
        return "/modules/sys/jobmanage/" + s;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initPage() {
        return getView("query");
    }

    /**
     * 初始化数据
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid query(@ModelAttribute TaskJobFilter filter) {

        SysPrincipal sysPrincipal = SysUserUtils.getSysPrincipal();


        System.out.println("---------------进入---------------");
        List<TaskJob> list = taskJobService.getTaskLists(filter);
        return coverJqGrid(filter, list);
    }

    @RequestMapping("/filter")
    public String filter(@ModelAttribute TaskJobFilter filter, Model model) {
        return getView("filter");
    }


    /**
     * ----------------打开手动新建任务
     *
     * @param model
     * @return url
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String showAddView(@ModelAttribute TaskJobFilter filter, Model model) {
        model.addAttribute("taskjob", filter);
        return getView("creatTaskForm");
    }

    /**
     * ------------保存手动新建任务提交
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Message create(@ModelAttribute TaskJobFilter filter) {
        taskJobService.saveTaskJob(filter);
        return coverMessage("200");
    }

    /**
     * ---------修改查看任务详情---------------
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String showEdit(Model model, @PathVariable String id) {
        TaskJob task = taskJobService.getById(id);
        model.addAttribute("taskjob", task);
        return getView("editForm");
    }

    /**
     * --------------------修改任务----------------
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Message editTaskJob(@ModelAttribute TaskJobFilter filter) {

        TaskJob task = taskJobService.getById(filter.getSysId());
        if (ObjectUtils.isBlank(task)) {
            return coverMessage("500", "找不到该任务，请刷新页面");
        }
        taskJobService.updateTaskJob(filter, task);
        return coverMessage("200", "任务创建成功");


    }

    /**
     * ---------------项目立项---------------
     */
    @RequestMapping(value = "/approvalItem", method = RequestMethod.GET)
    public String showApprovalview(Model model) {
        BookFilter bf = new BookFilter();
        TaskJob task = new TaskJob();
        model.addAttribute("taskjob", task);

        //获取督查组
        List<JobGroup> listgroup = jobGroupService.getJobGroup(new JobGroupFilter());

        //单位通讯录
        List<AddressBook> listbooks = bookService.getBooks(bf);
        // 人员通讯录
        List<AddressBookUser> userlist = bookUserService.queryByFilter(new BookFilter());

        model.addAttribute("bookLists", listbooks);
        model.addAttribute("groupList", listgroup);
        model.addAttribute("userLists", userlist);


        return getView("approvalFrom");
    }

    @ResponseBody
    @RequestMapping(value = "/approvalItemCreate", method = RequestMethod.POST)
    public Message createApproval(@ModelAttribute TaskJobFilter filter) {
        if (StringUtils.isBlank(filter.getTaskType())) {
            return coverMessage("500", "事件类型不能为空，请重新选择");
        }
        TaskJob taskJob = taskJobService.saveApprovalItem(filter); //保存立项工作
        TaskProcessFilter processFilter = new TaskProcessFilter();
        processFilter.setTaskId(taskJob.getSysId());
        processFilter.setRespDept(taskJob.getResDept());
        processFilter.setRespCode(taskJob.getRespCode());
        processService.saveProcessJob(processFilter);
        return coverMessage("200");
    }

    /**
     * signtask 任务签收操作
     */
    @RequestMapping(value = "/signTask/{id}", method = RequestMethod.GET)
    public String showSignTask(Model model, @PathVariable String id, TaskProcessFilter filter) {
        /* TaskProcessFilter filter  = new TaskProcessFilter();*/

        // List<TaskProcess>   processList =  processService.getProcessList(filter);
      /*  Map<String,String> stages  = new HashMap<>();
        stages.put("1","承办");
        stages.put("2","承办");*/


        TaskJob job = taskJobService.getById(id);
        filter.setTaskId(id);
        filter.setOrderBy("asc");
        List<TaskProcess> processes = processService.getProcessList(filter);
        List<FlowLineBean> listline = new ArrayList<>();
        for (TaskProcess item : processes) {
            BookFilter bf = new BookFilter();
            bf.setDeptCode(item.getRespCode());
            bf.setDeptName(item.getRespUser());

            /*AddressBook book  = bookUserService.queryByFilter(bf);*/

            FlowLineBean bean = new FlowLineBean();
            bean.setCreateDate(item.getCreateDate() + " " + item.getCreateTime());
            // bean.setStage(item.getNodeId()=="1");
            bean.setStage(item.getNodestage());
            bean.setFlowId(item.getSysId());
            bean.setRespDept(item.getRespDept());
            bean.setTelphone("13779966921");
            bean.setRespUser(item.getRespUser());
            listline.add(bean);
        }


        BookFilter bf = new BookFilter();
        List<AddressBook> bookLists = bookService.getBooks(bf);
        List<AddressBookUser> bookUsers = bookUserService.query();


        model.addAttribute("bookLists", bookLists);
        model.addAttribute("bookUsers", bookUsers);
        model.addAttribute("taskProcess", filter);
        model.addAttribute("taskjob", job);
        model.addAttribute("listLine", listline);
        return getView("signForFrom");
    }

    @ResponseBody
    @RequestMapping(value = "/signTask", method = RequestMethod.POST)
    public Message updateTaskProcess(@ModelAttribute TaskProcessFilter filter) {
        System.out.println("已签收");
        // TaskJob job = taskJobService.getById(filter.getSysId());
        TaskProcessFilter tf = new TaskProcessFilter();
        tf.setNodeid("1");
        tf.setTaskId(filter.getTaskId());
        // tf.setTaskId(filter.getSysId());
        List<TaskProcess> process = processService.getProcessList(tf);
        TaskProcess tp = process.get(0);
        tp.setState("1"); //已签收
        tp.setRespUser(tp.getRespDept());
        processService.update(tp);
        /* TaskProcess  tp2 = new TaskProcess();*/
        processService.saveOrUpdateJob(filter);
        return coverMessage("200");
    }

    /**
     * -----------------------节点图流程---------------------
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping("/getTaskNodes")
    public Message getTaskNodes(@RequestBody TaskJobFilter filter) {
        //流程图阶段拼接
        String[] allNodes = {"任务生成", "任务开始", "任务执行中", "任务完成", "任务未完成", "反馈攻坚", "完成情况", "督查记录", "督察组需协调事项", "责任单位需协调事项", "督查得分"};

        List<GraphBean> lists = new ArrayList<>();
        GraphBean bean = new GraphBean();
        bean.setSource("任务生成");
        bean.setTarget("任务开始");
        lists.add(bean);
        bean = new GraphBean();
        bean.setSource("任务开始");
        bean.setTarget("任务执行中");
        lists.add(bean);


        TaskJob task = taskJobService.getById(filter.getSysId());


        //判断是否有督查记录

     /* List<SupervisionLog> logs = supervisionLogService.getMissionLog(task.getSysId());
        if(ObjectUtils.isNotBlank(logs))
        {
            bean  = new GraphBean();
            bean.setSource("任务执行中");
            bean.setTarget("督查记录");
            lists.add(bean);

        }
        //是否有完成情况
        List<TaskRecord> records = taskRecordService.getRecordsById(task.getSysId());
        if(ObjectUtils.isNotBlank(records))
        {
            bean  = new GraphBean();
            bean.setSource("任务执行中");
            bean.setTarget("完成情况");
            lists.add(bean);
        }*/
        if ("1".equals(task.getTaskResult())) //任务是否完成 1 完成
        {
            bean = new GraphBean();
            bean.setSource("任务执行中");
            bean.setTarget("任务完成");
            lists.add(bean);
            bean = new GraphBean();
            bean.setSource("任务完成");
            bean.setTarget("督查得分");
            lists.add(bean);
        } else {  // 未完成
            Date planEnd = null;
            Date enddate = null;
            try {
                planEnd = UtilsTools.StringToDate(task.getPlanEndDate());
                enddate = UtilsTools.StringToDate(UtilsTools.getCurrentDate());
                if (planEnd.compareTo(enddate) < 0)   //15天后 是否完成
                {
                    bean = new GraphBean();
                    bean.setSource("任务执行中");
                    bean.setTarget("任务未完成");
                    lists.add(bean);
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }

            if ("1".equals(task.getIsfeedback())) //未完成是否反馈给攻坚办
            {
                bean = new GraphBean();
                bean.setSource("任务未完成");
                bean.setTarget("反馈攻坚");
                lists.add(bean);

                if ("1".equals(task.getTaskResult()))//再次判断任务是否完成
                {

                    bean = new GraphBean();
                    bean.setSource("反馈攻坚");
                    bean.setTarget("督查得分");
                    lists.add(bean);

                } else {
                    //判断是否再次生成任务
                    bean = new GraphBean();
                    bean.setSource("反馈攻坚");
                    bean.setTarget("任务生成");
                    lists.add(bean);
                }
            }

        }

        Map<String, Object> map = new HashMap<>();
        map.put("graph", lists);
        int[] greenNode = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
        for (GraphBean item : lists) {
            for (int i = 0; i < allNodes.length; i++) {
                if (item.getTarget().equals(allNodes[i])) {
                    greenNode[i] = 0;
                }
            }
        }

        map.put("green", greenNode);

        return coverMessage("200", "successful", map);
    }

    /**
     * 点击导出对话框
     *
     * @param filter
     * @param model
     * @return
     */
    @RequestMapping(value = "/formHead", method = RequestMethod.GET)
    public String showExport(@ModelAttribute TaskJobFilter filter, Model model) {
        model.addAttribute("taskjob", filter);
        return getView("formHead");
    }

    @ResponseBody
    @RequestMapping(value = "/exportJobs", method = RequestMethod.GET)
    public void exportJobs(HttpServletResponse reponse, HttpServletRequest request, @ModelAttribute ExportHeads heads) {

        System.out.println(heads);
       /* String heads = request.getParameter("exportHead ");

        String[] sds = {"taskName",
                "aaa001",
                "resDept",
                "resUser",
                "taskResult",};*/
        HSSFWorkbook wb = exportService.getJobListData(heads.getExportHead());
        HSSFSheet sheet = wb.getSheetAt(0);
        int rownum = sheet.getLastRowNum();
        if (rownum == 0) {
            throw new SystemException("没有数据");
        }
        OutputStream out = null;
        try {
            out = reponse.getOutputStream();
            String nowDate = getNowDate();
            String filename = "任务清单" + nowDate + ".xls";
            reponse.setContentType("application/x-msdownload");
            reponse.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            wb.write(out);
        } catch (Exception e) {

        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * cancletask 撤销任务
     */
    @ResponseBody
    @RequestMapping(value = "/cancletask/{id}")
    public Message calcletask(@PathVariable List<String> id) {

        for (String item : id) {
            TaskJob job = taskJobService.getById(item);
            job.setAaa001("0"); // 0 失效任务
            taskJobService.update(job);
        }

        return coverMessage("200");
    }

    /**
     * cancletask 撤销任务
     */
    @ResponseBody
    @RequestMapping(value = "/freebacktask/{id}")
    public Message freebacktask(@PathVariable List<String> id) {

        for (String item : id) {
            TaskJob job = taskJobService.getById(item);
            job.setAaa001("2");  // 2 回退
            taskJobService.update(job);
        }

        return coverMessage("200");
    }


    @Autowired
    private TaskSituationService taskSituationService;

    /**
     * 添加落实情况
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/creatTaskSituation", method = RequestMethod.POST)
    public Message creatTaskSituation(@ModelAttribute TaskSituationFilter filter) {
        filter.setTaskId(filter.getSysId());
        filter.setSysId(null);
        taskSituationService.saveTaskSituation(filter);
        return coverMessage("200", "创建成功", true);
    }

    /**
     * 打开落实情况按钮
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/creatTaskSituation/{id}", method = RequestMethod.GET)
    public String showTaskSituasion(@PathVariable String id, Model model) {
        //任务
        TaskJob taskJob = taskJobService.getById(id);
        List<TaskSituation> list = taskSituationService.getTaskId(id);

        //获取督查组
        List<JobGroup> listgroup = jobGroupService.getJobGroup(new JobGroupFilter());

        //单位通讯录
        List<AddressBook> listbooks = bookService.getBooks(new BookFilter());
        // 人员通讯录
        List<AddressBookUser> userlist = bookUserService.queryByFilter(new BookFilter());

        model.addAttribute("bookLists", listbooks);
        model.addAttribute("groupList", listgroup);
        model.addAttribute("userLists", userlist);

        model.addAttribute("taskjob", taskJob);
        model.addAttribute("situationList", list);
        return getView("situationForm");

    }

}
